//
//  FCache.m
//  Foundation
//
//  Created by 三井 on 2019/10/23.
//

#import "FCache.h"
#import "DYLaunchEventManager.h"

@interface FCache ()

@end

@implementation FCache

+ (instancetype)cacheForKey:(NSString *)key {
    FCache *cache = [[self alloc] init];
    cache.key = key;
    return cache;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)push:(NSObject *)obj {
    FCacheItem *item = [self.items jk_detect:^BOOL(FCacheItem *object) {
        return [object.object isEqual:obj];
    }];
    if (item) {
        [item visit];
        [self.items removeObject:item];
        [self.items insertObject:item atIndex:0];
        return;
    }
    
    [self.items insertObject:[FCacheItem itemWithObject:obj] atIndex:0];
    ExecuteLater({
        [self flush];
    });
}

- (FCacheItem *)peek {
    return self.items.lastObject;
}

- (FCacheItem *)pop {
    FCacheItem *item = self.items.lastObject;
    [self.items removeLastObject];
    return item;
}

- (NSArray<FCacheItem *> *)peek:(NSUInteger)num {
    return [self.items subarrayWithRange:NSMakeRange(0, MIN(num, self.items.count))];
}

- (void)flush {
    [[NSUserDefaults standardUserDefaults] setObject:[self.items yy_modelToJSONObject] forKey:self.key];
}

- (NSMutableArray<FCacheItem *> *)items {
    if (!_items) {
        if (self.key.length > 0) {
            NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:self.key];
            if (!arr) {
                _items = [NSMutableArray array];
            } else {
                NSArray *itemArr = [NSArray yy_modelArrayWithClass:FCacheItem.class json:arr];
                _items = [NSMutableArray arrayWithArray:itemArr];
            }
        }
    }
    return _items;
}

@end
